package xq.gwt.ui.crud;

import xq.gwt.mvc.model.BooleanPropertyModel;
import xq.gwt.mvc.model.CommandModel;
import xq.gwt.mvc.model.EntityModel;
import xq.gwt.mvc.model.PropertyModel;
import xq.gwt.mvc.model.StringPropertyModel;
import xq.gwt.ui.crud.localization.CrudDictionary;

public class CancelEntityEditCommand implements CommandModel{	
	
	private static final long serialVersionUID = -4691353837456600286L;
	private BooleanPropertyModel enabled = new BooleanPropertyModel();
	private EntityModel entity;
	private StringPropertyModel[] savedProps;

	
	public CancelEntityEditCommand(){
		updateEnabled();
	}
	
	@Override
	public void execute() throws Exception {
		undoEntityChanges();		
	}

	
	public void setEntity(EntityModel entity) {
		this.entity = entity;
		saveEntityProps();
		updateEnabled();
	}

	private void saveEntityProps(){
		PropertyModel[] props = null;
		if(this.entity != null){
			props = this.entity.getProperties();
		}		
		
		if(props == null){
			savedProps = null;
			return;
		}
		savedProps = new StringPropertyModel[props.length];
		for (int i = 0; i < props.length; i++) {
			savedProps[i] = new StringPropertyModel();
			savedProps[i].setText(props[i].getText());
		}		
	}
	
	private void undoEntityChanges() throws Exception {
		if(savedProps == null){			
			return;
		}
		if (this.entity == null){
			return;
		}
		
		for (int i = 0; i < savedProps.length; i++) {
			this.entity.getProperties()[i].setText(savedProps[i].getText());
		}		
				
	}
	
	private void updateEnabled(){
		if(entity == null){
			enabled.setValue(false);
		}
		else{
			enabled.setValue(true);
		}		
	}
	
	@Override
	public String getCaption() {		
		return CrudDictionary.Constants().cancelEdit_caption();
	}

	@Override
	public String getName() {		
		return "Cancel";
	}

	@Override
	public BooleanPropertyModel isEnabled() {		
		return enabled;
	}

	@Override
	public String getFeedback() {		
		return null;
	}

}
